import { createReadStream, existsSync, statSync } from "fs";
import { join, extname } from "path";

export default defineEventHandler(async (event) => {
  // 只处理 /uploads/** 路径的请求
  if (!event.path.startsWith("/uploads/")) {
    return;
  }

  // 确保uploads目录存在
  const uploadsDir = join(useRuntimeConfig().rootPath, "uploads");

  // 构建实际文件路径
  let relativePath = event.path.replace("/uploads/", "");
  // 解码URL中的中文字符
  relativePath = decodeURIComponent(relativePath);
  const filePath = join(uploadsDir, relativePath);

  // 防止目录遍历攻击
  if (!filePath.startsWith(uploadsDir) || filePath.includes("..")) {
    return;
  }

  // 检查文件是否存在
  if (!existsSync(filePath) || !statSync(filePath).isFile()) {
    return;
  }

  // 获取文件MIME类型
  const ext = extname(filePath).toLowerCase();
  let contentType = "application/octet-stream";

  switch (ext) {
    case ".jpg":
    case ".jpeg":
      contentType = "image/jpeg";
      break;
    case ".png":
      contentType = "image/png";
      break;
    case ".gif":
      contentType = "image/gif";
      break;
    case ".webp":
      contentType = "image/webp";
      break;
    case ".svg":
      contentType = "image/svg+xml";
      break;
    case ".pdf":
      contentType = "application/pdf";
      break;
    case ".txt":
      contentType = "text/plain";
      break;
    case ".css":
      contentType = "text/css";
      break;
    case ".js":
      contentType = "application/javascript";
      break;
    case ".json":
      contentType = "application/json";
      break;
  }

  // 设置响应头
  setHeader(event, "Content-Type", contentType);
  setHeader(event, "Cache-Control", "public, max-age=31536000");

  // 读取并发送文件
  const fileStream = createReadStream(filePath);
  return sendStream(event, fileStream);
});
